package com.wheatek.wtklib.net

import android.app.Application
import com.wheatek.wtklib.net.interceptor.LogInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit

object OkHttpUtils {

    private const val DEFAULT_TIMEOUT = 15L

    // log interceptor
    private val mLoggingInterceptor: Interceptor by lazy { LogInterceptor() }

    private var cer: String? = null

    private var mContext: Application? = null

    private val mClient: OkHttpClient by lazy { generateClient(cer, null) }

    fun getClient(context: Application, cer: String?): OkHttpClient {
        OkHttpUtils.cer = cer
        mContext = context
        return mClient
    }

    private fun generateClient(cer: String?, interceptor: Interceptor?): OkHttpClient {
        val builder = OkHttpClient.Builder().apply {
            connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            retryOnConnectionFailure(true)
//            hostnameVerifier(SSLSocketClient.getHostnameVerifier())
        }
        interceptor?.let {
            builder.addInterceptor(interceptor)
        }

        builder.addNetworkInterceptor(mLoggingInterceptor)
//        if (BuildConfig.DEBUG) {
//            builder.addNetworkInterceptor(mLoggingInterceptor)
//        } else {
//            builder.proxy(Proxy.NO_PROXY)
//        }
        if (cer.isNullOrEmpty()) {
            // 信任所有证书
            SSLCerUtils.setTrustAllCertificate(builder)
        } else {
            // https证书
            SSLCerUtils.setCertificate(mContext, builder, cer)
        }

        return builder.build()
    }
}